<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 对象数组
    const cityArr = [
        {id: 1, pid: 0, name: '安徽省'},
          {id: 2, pid: 1, name: '合肥市'},
          {id: 3, pid: 1, name: '芜湖市'},
          {id: 4, pid: 1, name: '黄山市'},
          {id: 9, pid: 4, name: '歙县'},
        {id: 5, pid: 0, name: '广东省'},
          {id: 6, pid: 5, name: '广州市'},
          {id: 7, pid: 5, name: '深圳市'},
        {id: 8, pid: 0, name: '江苏省'}
    ]

    /*
     * list: 对象数组
     * flag: 转化的层级(pid)
     */  
    function transListArrToTreeArr(list, flag){
        // 1. 定义一个数组
        const treeArr = []
        // 2. 遍历对象数组
        list.forEach((item)=>{
            // 2.1 判断
            if(item.pid === flag){
              // 一级 ===> item
              // 一级里面可能有二级 ===?==> 如何知道有二级?
              const tempArr = transListArrToTreeArr(list, item.id)
              // 2.2 判断有没有子级
              if(tempArr.length > 0){
                 item.children = tempArr
              }
              treeArr.push(item)
            }
        })
        // 3. 返回数组
        return treeArr
    }

    // 调用
    const res = transListArrToTreeArr(cityArr, 0)
    console.log(res)
  </script>
</body>
</html>